package com.woohua.demo.thread;


import org.apache.commons.lang.StringUtils;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @version 1.0
 * @author: woo hua
 * @DATE 2022/7/21 8:53
 * @description:自定义线程工厂
 */
@SuppressWarnings("serial")
public class CustomThreadFactory implements ThreadFactory {

    /**
     * 线程前缀，采用 AtomicInteger实现线程编号线程安全自增
     */
    private final AtomicInteger atomicInteger = new AtomicInteger(1);

    /**
     * 线程命名前缀
     */
    private String namePrefix;

    /**
     * 线程创建的过程是否守护线程
     */
    private boolean isDaemon;

    public CustomThreadFactory(String namePrefix, boolean isDaemon) {
        if(StringUtils.isNotEmpty(namePrefix)) {
            this.namePrefix = namePrefix;
        }else {
            this.namePrefix = "thread_pool";
        }
        // 是否是守护线程
        this.isDaemon = isDaemon;
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r, namePrefix + "." + atomicInteger.getAndDecrement());
        thread.setDaemon(isDaemon);
        if(Thread.NORM_PRIORITY != thread.getPriority()) {
            thread.setPriority(Thread.NORM_PRIORITY);
        }
        return thread;
    }
}
